package jmf.network;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import javax.media.Time;
import javax.media.protocol.ContentDescriptor;
import javax.media.protocol.InputSourceStream;
import javax.media.protocol.PullDataSource;
import javax.media.protocol.PullSourceStream;

public class NetworkRawDataSource extends PullDataSource {
  private static final ContentDescriptor contentDescriptor =
    new ContentDescriptor("video.mpeg");

  private String host;
  private Socket socket;

  public NetworkRawDataSource(String h) {
    host = h;
    socket = null;
  }

  @Override
  public void connect() throws IOException {
    socket = new Socket(host, ProtocolConstants.SERVER_PORT);
  }

  @Override
  public void start() throws IOException {
  }

  public PullSourceStream[] getStreams() {
    InputStream inputStream = null;

    try {
      inputStream = new BufferedInputStream(socket.getInputStream());
    } catch (Exception e) {
      return null;
    }

    /*PullSourceStream sourceStream = new InputSourceStream(
      inputStream, NetworkRawDataSource.contentDescriptor
    );*/

    PullSourceStream sourceStream = new NetworkRawSourceStream(
      inputStream, NetworkRawDataSource.contentDescriptor
    );

    PullSourceStream[] v = { sourceStream };
    return v;
  }

  @Override
  public void stop() throws IOException {
  }

  @Override
  public void disconnect() {
    try {
      socket.close();
    } catch (IOException e) {
    } finally {
      socket = null;
    }
  }

  @Override
  public Object getControl(String c) {
    return null;
  }

  @Override
  public Object[] getControls() {
    return new Object[0];
  }

  @Override
  public String getContentType() {
    return NetworkRawDataSource.contentDescriptor.getContentType();
  }

  @Override
  public Time getDuration() {
    return DURATION_UNKNOWN;
  }
}
